using System;
using System.Text;

namespace SKBKontur.Serialization.Binding
{
    public class DateTimeBinder : ScalarBinder
    {
        public DateTimeBinder(string columnName) : base(columnName)
        {
        }

        public DateTimeBinder()
        {
        }

        public override byte[] SerializeValue(object value)
        {
            return Encoding.UTF8.GetBytes(String.Format("{0:yyyyMMddHHmmssfff}", ((DateTime) value).ToUniversalTime()));
        }

        public override object UnserializeValue(Type type, byte[] data)
        {
            string str = Encoding.UTF8.GetString(data);
            int year = Convert.ToInt32(str.Substring(0, 4));
            int mounth = Convert.ToInt32(str.Substring(4, 2));
            int day = Convert.ToInt32(str.Substring(6, 2));
            int hour = Convert.ToInt32(str.Substring(8, 2));
            int minute = Convert.ToInt32(str.Substring(10, 2));
            int second = Convert.ToInt32(str.Substring(12, 2));
            int millisecond = Convert.ToInt32(str.Substring(14, 3));
            return new DateTime(year, mounth, day, hour, minute, second, millisecond, DateTimeKind.Utc).ToLocalTime();
        }
    }
}